package com.sugon.projectManager.controller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.sugon.common.annotation.Log;
import com.sugon.common.core.controller.BaseController;
import com.sugon.common.core.domain.AjaxResult;
import com.sugon.common.enums.BusinessType;
import com.sugon.projectManager.domain.ProjectInfo;
import com.sugon.projectManager.service.IProjectInfoService;
import com.sugon.common.utils.poi.ExcelUtil;
import com.sugon.common.core.page.TableDataInfo;
import com.sugon.common.utils.SecurityUtils;

/**
 * 工程项目信息Controller
 * 
 * @author ERIC
 * @date 2025-10-20
 */
@RestController
@RequestMapping("/projectManager/project")
public class ProjectInfoController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(ProjectInfoController.class);
    
    @Autowired
    private IProjectInfoService projectInfoService;

    /**
     * 查询工程项目信息列表
     */
    @PreAuthorize("@ss.hasPermi('projectManager:project:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProjectInfo projectInfo)
    {
        startPage();
        List<ProjectInfo> list = projectInfoService.selectProjectInfoList(projectInfo);
        return getDataTable(list);
    }

    /**
     * 导出工程项目信息列表
     */
    @PreAuthorize("@ss.hasPermi('projectManager:project:export')")
    @Log(title = "工程项目信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(ProjectInfo projectInfo, HttpServletRequest request, HttpServletResponse response)
    {
        try
        {
            // 查询数据，不分页（导出所有符合条件的数据）
            List<ProjectInfo> list = projectInfoService.selectProjectInfoListForExport(projectInfo);
            
            // 获取前端传递的字段选择参数
            String selectedColumnsStr = request.getParameter("selectedColumns");
            String[] selectedColumns = null;
            if (selectedColumnsStr != null && !selectedColumnsStr.trim().isEmpty()) {
                // 清理可能的空格和处理数组格式
                String cleanStr = selectedColumnsStr.replaceAll("[\\[\\]\\s]", "");
                if (cleanStr.endsWith(",")) {
                    cleanStr = cleanStr.substring(0, cleanStr.length() - 1);
                }
                selectedColumns = cleanStr.split(",");
                logger.info("导出选择的字段: " + java.util.Arrays.toString(selectedColumns));
                
                ExcelUtil<ProjectInfo> util = new ExcelUtil<ProjectInfo>(ProjectInfo.class);
                util.exportExcelByColumns(response, list, "工程项目信息", selectedColumns);
            } else {
                logger.info("导出所有字段，未指定选择字段");
                ExcelUtil<ProjectInfo> util = new ExcelUtil<ProjectInfo>(ProjectInfo.class);
                util.exportExcel(response, list, "工程项目信息");
            }
        }
        catch (Exception e)
        {
            logger.error("导出工程项目信息失败", e);
            // 设置错误响应
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("application/json;charset=UTF-8");
            try {
                response.getWriter().write("{\"code\":500,\"msg\":\"导出失败：" + e.getMessage() + "\"}");
            } catch (Exception ex) {
                logger.error("写入错误响应失败", ex);
            }
        }
    }

    /**
     * 获取工程项目信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('projectManager:project:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(projectInfoService.selectProjectInfoById(id));
    }

    /**
     * 新增工程项目信息
     */
    @PreAuthorize("@ss.hasPermi('projectManager:project:add')")
    @Log(title = "工程项目信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProjectInfo projectInfo)
    {
        return toAjax(projectInfoService.insertProjectInfo(projectInfo));
    }

    /**
     * 修改工程项目信息
     */
    @PreAuthorize("@ss.hasPermi('projectManager:project:edit')")
    @Log(title = "工程项目信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProjectInfo projectInfo)
    {
        return toAjax(projectInfoService.updateProjectInfo(projectInfo));
    }

    /**
     * 删除工程项目信息
     */
    @PreAuthorize("@ss.hasPermi('projectManager:project:remove')")
    @Log(title = "工程项目信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(projectInfoService.deleteProjectInfoByIds(ids));
    }

    /**
     * 审核工程项目信息
     */
    @PreAuthorize("@ss.hasPermi('projectManager:project:review')")
    @Log(title = "工程项目信息", businessType = BusinessType.UPDATE)
    @PutMapping("/review")
    public AjaxResult review(@RequestBody ProjectInfo projectInfo)
    {
        return toAjax(projectInfoService.updateProjectInfo(projectInfo));
    }

    /**
     * 导入工程项目数据
     */
    @PreAuthorize("@ss.hasPermi('projectManager:project:import')")
    @Log(title = "工程项目信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, Boolean updateSupport) throws Exception
    {
        try {
            if (file == null || file.isEmpty()) {
                throw new RuntimeException("请选择要导入的文件！");
            }
            
            // 检查文件类型
            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.toLowerCase().endsWith(".xls") && !fileName.toLowerCase().endsWith(".xlsx"))) {
                throw new RuntimeException("只支持 .xls 或 .xlsx 格式的Excel文件！");
            }
            
            logger.info("开始导入Excel文件：" + fileName + ", 大小：" + file.getSize() + " bytes");
            
            // 如果updateSupport为null，默认设置为true（勾选状态）
            if (updateSupport == null) {
                updateSupport = true;
                logger.info("是否更新已存在的项目数据：默认设置为true（勾选状态）");
            }
            
            ExcelUtil<ProjectInfo> util = new ExcelUtil<ProjectInfo>(ProjectInfo.class);
            List<ProjectInfo> projectList = util.importExcel(file.getInputStream());
            
            if (projectList == null || projectList.isEmpty()) {
                throw new RuntimeException("导入的数据为空，请检查Excel文件格式是否正确！");
            }
            
            logger.info("成功解析Excel数据，共 " + projectList.size() + " 条记录，是否更新已存在项目：" + updateSupport);
            
            String operName = SecurityUtils.getUsername();
            String message = importProject(projectList, updateSupport, operName);
            return AjaxResult.success(message);
        } catch (Exception e) {
            logger.error("导入工程项目数据失败：", e);
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }

    /**
     * 导入工程项目数据实现
     */
    public String importProject(List<ProjectInfo> projectList, Boolean updateSupport, String operName)
    {
        logger.info("开始导入项目数据，共 " + (projectList != null ? projectList.size() : 0) + " 条记录");
        
        if (projectList == null || projectList.isEmpty())
        {
            throw new RuntimeException("导入项目数据不能为空！");
        }
        
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        for (int i = 0; i < projectList.size(); i++)
        {
            ProjectInfo project = projectList.get(i);
            logger.info("处理第 " + (i + 1) + " 条记录，项目名称：" + (project.getProjectName() != null ? project.getProjectName() : "空"));
            
            try
            {
                // 检查项目名称是否为空
                if (project.getProjectName() == null || project.getProjectName().trim().isEmpty())
                {
                    failureNum++;
                    String projectInfo = "工程项目：" + (project.getProjectName() != null ? project.getProjectName() : "空") + 
                                      "，采购项目：" + (project.getProcurementProjectName() != null ? project.getProcurementProjectName() : "空");
                    failureMsg.append("<br/>" + (i + 1) + "、" + projectInfo + " - 项目名称不能为空");
                    continue;
                }
                
                // 检查采购项目名称是否为空
                if (project.getProcurementProjectName() == null || project.getProcurementProjectName().trim().isEmpty())
                {
                    failureNum++;
                    String projectInfo = "工程项目：" + (project.getProjectName() != null ? project.getProjectName() : "空") + 
                                      "，采购项目：" + (project.getProcurementProjectName() != null ? project.getProcurementProjectName() : "空");
                    failureMsg.append("<br/>" + (i + 1) + "、" + projectInfo + " - 采购项目名称不能为空");
                    continue;
                }
                
                // 检查是否已存在（根据采购项目名称，这是唯一约束字段）- 使用精确匹配查询
                List<ProjectInfo> existingProjects = projectInfoService.selectProjectInfoByProcurementName(project.getProcurementProjectName());
                
                if (!existingProjects.isEmpty() && !updateSupport)
                {
                    failureNum++;
                    String projectInfo = "工程项目：" + (project.getProjectName() != null ? project.getProjectName() : "空") + 
                                      "，采购项目：" + (project.getProcurementProjectName() != null ? project.getProcurementProjectName() : "空");
                    failureMsg.append("<br/>" + (i + 1) + "、" + projectInfo + " - 采购项目已存在");
                    continue;
                }
                
                if (!existingProjects.isEmpty() && updateSupport)
                {
                    // 更新现有项目
                    ProjectInfo existingProject = existingProjects.get(0);
                    logger.info("更新现有项目，ID：" + existingProject.getId());
                    
                    // 直接处理财务审计和评审字段
                    if ("是".equals(project.getIsFinancialAuditCompleted())) {
                        project.setIsFinancialAuditCompleted("1");
                    } else {
                        project.setIsFinancialAuditCompleted("0");
                    }
                    
                    if ("是".equals(project.getIsFinancialReviewCompleted())) {
                        project.setIsFinancialReviewCompleted("1");
                    } else {
                        project.setIsFinancialReviewCompleted("0");
                    }
                    
                    // 复制导入数据到现有项目
                    copyProjectData(project, existingProject);
                    projectInfoService.updateProjectInfo(existingProject);
                    successNum++;
                    String projectInfo = "工程项目：" + (project.getProjectName() != null ? project.getProjectName() : "空") + 
                                      "，采购项目：" + (project.getProcurementProjectName() != null ? project.getProcurementProjectName() : "空");
                    successMsg.append("<br/>" + (i + 1) + "、" + projectInfo + " - 更新成功");
                }
                else
                {
                    // 新增项目
                    logger.info("新增项目");
                    
                    // 合同编号和合同名称可以为空，用户在编辑时自行维护

                    // 设置默认状态为-1（未处理）
                    if (project.getStatus() == null || project.getStatus().trim().isEmpty()) {
                        project.setStatus("-1");
                        logger.info("项目 " + project.getProjectName() + " 状态为空，已设置为默认值: -1");
                    }
                    
                    // 直接处理财务审计和评审字段
                    if ("是".equals(project.getIsFinancialAuditCompleted())) {
                        project.setIsFinancialAuditCompleted("1");
                    } else {
                        project.setIsFinancialAuditCompleted("0");
                    }
                    
                    if ("是".equals(project.getIsFinancialReviewCompleted())) {
                        project.setIsFinancialReviewCompleted("1");
                    } else {
                        project.setIsFinancialReviewCompleted("0");
                    }
                    
                    projectInfoService.insertProjectInfo(project);
                    successNum++;
                    String projectInfo = "工程项目：" + (project.getProjectName() != null ? project.getProjectName() : "空") + 
                                      "，采购项目：" + (project.getProcurementProjectName() != null ? project.getProcurementProjectName() : "空");
                    successMsg.append("<br/>" + (i + 1) + "、" + projectInfo + " - 导入成功");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                logger.error("第 " + (i + 1) + " 条记录导入失败：", e);
                String projectInfo = "工程项目：" + (project.getProjectName() != null ? project.getProjectName() : "未知") + 
                                  "，采购项目：" + (project.getProcurementProjectName() != null ? project.getProcurementProjectName() : "未知");
                String msg = "<br/>" + (i + 1) + "、" + projectInfo + " - 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        
        logger.info("导入完成，成功：" + successNum + "，失败：" + failureNum);
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new RuntimeException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    
    /**
     * 复制项目数据
     */
    private void copyProjectData(ProjectInfo source, ProjectInfo target)
    {
        if (source.getProjectName() != null) target.setProjectName(source.getProjectName());
        if (source.getApprovalAuthority() != null) target.setApprovalAuthority(source.getApprovalAuthority());
        if (source.getApprovalDocument() != null) target.setApprovalDocument(source.getApprovalDocument());
        if (source.getApprovalDate() != null) target.setApprovalDate(source.getApprovalDate());
        if (source.getPreliminaryDesignDocument() != null) target.setPreliminaryDesignDocument(source.getPreliminaryDesignDocument());
        if (source.getPreliminaryDesignDate() != null) target.setPreliminaryDesignDate(source.getPreliminaryDesignDate());
        if (source.getApprovedConstructionContent() != null) target.setApprovedConstructionContent(source.getApprovedConstructionContent());
        if (source.getApprovedBudget() != null) target.setApprovedBudget(source.getApprovedBudget());
        if (source.getProcurementProjectName() != null) target.setProcurementProjectName(source.getProcurementProjectName());
        if (source.getProcurementCategory() != null) target.setProcurementCategory(source.getProcurementCategory());
        if (source.getProcurementContent() != null) target.setProcurementContent(source.getProcurementContent());
        if (source.getProcurementMethod() != null) target.setProcurementMethod(source.getProcurementMethod());
        if (source.getProcurementAgent() != null) target.setProcurementAgent(source.getProcurementAgent());
        if (source.getAnnouncementTime() != null) target.setAnnouncementTime(source.getAnnouncementTime());
        if (source.getAnnouncementPlatform() != null) target.setAnnouncementPlatform(source.getAnnouncementPlatform());
        if (source.getBidderContactInfo() != null) target.setBidderContactInfo(source.getBidderContactInfo());
        if (source.getBiddingParticipants() != null) target.setBiddingParticipants(source.getBiddingParticipants());
        if (source.getWinningBidder() != null) target.setWinningBidder(source.getWinningBidder());
        if (source.getReviewLocation() != null) target.setReviewLocation(source.getReviewLocation());
        if (source.getReviewTime() != null) target.setReviewTime(source.getReviewTime());
        if (source.getOwnerRepresentative() != null) target.setOwnerRepresentative(source.getOwnerRepresentative());
        if (source.getOwnerRepresentativeContact() != null) target.setOwnerRepresentativeContact(source.getOwnerRepresentativeContact());
        if (source.getWinningAnnouncementTime() != null) target.setWinningAnnouncementTime(source.getWinningAnnouncementTime());
        if (source.getWinningAnnouncementPlatform() != null) target.setWinningAnnouncementPlatform(source.getWinningAnnouncementPlatform());
        if (source.getWinningBidAmount() != null) target.setWinningBidAmount(source.getWinningBidAmount());
        if (source.getSettlementAmount() != null) target.setSettlementAmount(source.getSettlementAmount());
        if (source.getContractName() != null) target.setContractName(source.getContractName());
        if (source.getContractNumber() != null) target.setContractNumber(source.getContractNumber());
        if (source.getContractContent() != null) target.setContractContent(source.getContractContent());
        if (source.getNegotiationDate() != null) target.setNegotiationDate(source.getNegotiationDate());
        if (source.getContractSignDate() != null) target.setContractSignDate(source.getContractSignDate());
        if (source.getContractAmount() != null) target.setContractAmount(source.getContractAmount());
        if (source.getPartyASignatory() != null) target.setPartyASignatory(source.getPartyASignatory());
        if (source.getPartyBSignatory() != null) target.setPartyBSignatory(source.getPartyBSignatory());
        if (source.getProjectManager() != null) target.setProjectManager(source.getProjectManager());
        if (source.getSiteRepresentativePartyA() != null) target.setSiteRepresentativePartyA(source.getSiteRepresentativePartyA());
        if (source.getHandlerPartyA() != null) target.setHandlerPartyA(source.getHandlerPartyA());
        if (source.getHandlerPartyB() != null) target.setHandlerPartyB(source.getHandlerPartyB());
        if (source.getFinalSettlementAmount() != null) target.setFinalSettlementAmount(source.getFinalSettlementAmount());
        if (source.getIsFinancialAuditCompleted() != null) target.setIsFinancialAuditCompleted(source.getIsFinancialAuditCompleted());
        if (source.getIsFinancialReviewCompleted() != null) target.setIsFinancialReviewCompleted(source.getIsFinancialReviewCompleted());
        if (source.getComment() != null) target.setComment(source.getComment());
        if (source.getStatus() != null) target.setStatus(source.getStatus());
    }

    /**
     * 下载导入模板
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<ProjectInfo> util = new ExcelUtil<ProjectInfo>(ProjectInfo.class);
        return util.importTemplateExcel("工程项目数据");
    }
    

}